<template>
  <el-dialog :visible.sync="dialogTableVisible" :append-to-body="true" :lock-scroll="false" :title="isEdit?'Edit':'Create'" width="900px" @close="handleCloseDetailDialog">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="120px" style="margin-left:50px;">
      <el-form-item :label="$t('table.area')" required prop="area">
        <el-select v-model="postForm.area" clearable placeholder="Please Chose" width="600px" @change="changearea">
          <el-option v-for="item in areaOptions" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('couponfiles.discount_type')" required>
        <el-radio-group v-model="postForm.discount_type">
          <el-radio label="AMOUNT" value="AMOUNT">{{ $t('couponfiles.AMOUNT') }}</el-radio>
          <el-radio label="PERCENTAGE" value="PERCENTAGE">{{ $t('couponfiles.PERCENTAGE') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!--<template v-if="postForm.discount_type == 'AMOUNT' ">-->
      <!--<el-form-item :label="$t('table.Rule')">-->
      <!--<div class="grid-content bg-purple">-->
      <!--&lt;!&ndash;<el-col :span="3">&ndash;&gt;-->
      <!--&lt;!&ndash;<div class="grid-content bg-purple">&ndash;&gt;-->
      <!--&lt;!&ndash;<el-input v-model.number="postForm.couponrules[0].min_charge" name="min_charge[]" placeholder="Quantity"/>&ndash;&gt;-->
      <!--&lt;!&ndash;</div>&ndash;&gt;-->
      <!--&lt;!&ndash;</el-col>&ndash;&gt;-->
      <!--<el-col :span="3">{{ $t('couponfiles.reduce') }}</el-col>-->
      <!--<el-col :span="5">-->
      <!--<div class="grid-content bg-purple">-->
      <!--<el-input v-model="postForm.couponrules[0].min_charge" name="min_charge[]" placeholder=""/>-->
      <!--</div>-->
      <!--</el-col>-->
      <!--<el-col :span="1">{{ postForm.symbol }}</el-col>-->
      <!--</div>-->
      <!--</el-form-item>-->
      <!--</template>-->

      <!--<template v-if="postForm.discount_type == 'PERCENTAGE' ">-->
      <!--<el-form-item :label="$t('table.Rule')">-->
      <!--<div class="grid-content bg-purple">-->
      <!--<el-col :span="3">{{ $t('couponfiles.discount_off') }}</el-col>-->
      <!--<el-col :span="3">-->
      <!--<div class="grid-content bg-purple">-->
      <!--<el-input v-model="postForm.couponrules[0].discount_off" name="discount_off[]" placeholder=""/>-->
      <!--</div>-->
      <!--</el-col>-->
      <!--<el-col :span="1">%</el-col>-->
      <!--</div>-->
      <!--</el-form-item>-->
      <!--</template>-->
      <el-form-item :label="$t('table.type')" required prop="discount_type">
        <el-radio-group v-model="postForm.type">
          <el-radio :label="1">{{ $t('table.Online') }}</el-radio>
          <el-radio :label="2">{{ $t('table.Offline') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="postForm.type === 2">
        <el-form-item :label="$t('couponfiles.code')" prop="code">
          <el-col :span="20">
            <el-input v-model="postForm.code" />
          </el-col>
        </el-form-item>

      </template>

      <el-form-item :label="$t('table.available')" prop="is_available" required>
        <el-radio-group v-model="postForm.is_available">
          <el-radio :label="1">{{ $t('table_element.available.on') }}</el-radio>
          <el-radio :label="0">{{ $t('table_element.available.un') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('table.Rule')" prop="rule">
        <el-row v-for="(item, index) in postForm.couponrules" :gutter="10" :key="index">
          <el-col :span="3">{{ $t('couponfiles.min_charge') }}</el-col>
          <el-col :span="3">
            <div class="grid-content bg-purple">
              <el-input type="number" v-model.number="item.min_charge" name="min_charge[]"/>
            </div>
          </el-col>
          <el-col :span="5">{{ $t('couponfiles.min_cleanse_days') }}</el-col>
          <el-col :span="3">  
            <div class="grid-content bg-purple">
              <el-input v-model="item.min_cleanse_days" name="min_cleanse_days[]"/>
            </div>
          </el-col>
          <el-col :span="2">{{ $t('table.discount') }}</el-col>
          <el-col :span="3">
            <div class="grid-content bg-purple">
              <el-input type="number" v-model.number="item.discount_off" @blur="validDiscount(item)" name="discount_off[]"/>
            </div>
          </el-col>
          <el-button style="font-size:20px;" type="text" class="el-icon-remove-outline" @click="delcouponrule(index)" />
        </el-row>
        <el-row >
          <el-button style="font-size:20px;" type="text" class="el-icon-circle-plus-outline" @click="addcouponrule()" />
        </el-row>
      </el-form-item>

      <template>
        <el-tabs v-model="activeName">

          <el-tab-pane label="zh-tw" name="first">
            <el-form-item :label="$t('couponfiles.name')" prop="en_name" required>
              <el-col :span="20">
                <el-input v-model="postForm.en_name" />
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('couponfiles.description')" prop="en_description" >
              <el-col :span="20">
                <el-input v-model="postForm.en_description" type="textarea"/>
              </el-col>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="zh-ch" name="second">
            <el-form-item :label="$t('couponfiles.name')" prop="cn_name">
              <el-col :span="20">
                <el-input v-model="postForm.cn_name" />
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('couponfiles.description')" prop="cn_description" >
              <el-col :span="20">
                <el-input v-model="postForm.cn_description" type="textarea"/>
              </el-col>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="zh-hk" name="third">
            <el-form-item :label="$t('couponfiles.name')" prop="hk_name">
              <el-col :span="20">
                <el-input v-model="postForm.hk_name" />
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('couponfiles.description')" prop="hk_description" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_description" type="textarea"/>
              </el-col>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="zh-tw" name="fourth">
            <el-form-item :label="$t('couponfiles.name')" prop="tw_name">
              <el-col :span="20">
                <el-input v-model="postForm.tw_name" />
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('couponfiles.description')" prop="tw_description" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_description" type="textarea"/>
              </el-col>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </template>

      <!--<el-form-item :label="$t('couponfiles.code')" prop="code" required >-->
      <!--<el-col :span="20">-->
      <!--<el-input v-model="postForm.code"/>-->
      <!--</el-col>-->
      <!--</el-form-item>-->

      <el-form-item :label="$t('table.start_date')" prop="start_date" required>
        <el-col :span="20">
          <el-date-picker v-model="postForm.start_date" type="datetime" format="yyyy-MM-dd HH:mm:00" value-format="yyyy-MM-dd HH:mm:00" :placeholder="$t('placeholder.date')" style="width: 100%;"/>
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('table.end_date')" prop="end_date" required>
        <el-col :span="20">
          <el-date-picker v-model="postForm.end_date" type="datetime" format="yyyy-MM-dd HH:mm:00" value-format="yyyy-MM-dd HH:mm:00" :placeholder="$t('placeholder.date')" style="width: 100%;"/>
        </el-col>
      </el-form-item>

      <!--<el-form-item :label="$t('couponfiles.user_limit')" prop="user_limit" required >-->
      <!--<el-col :span="20">-->
      <!--<el-input v-model.number="postForm.user_limit" type="number"/>-->
      <!--</el-col>-->
      <!--</el-form-item>-->

      <!--<el-form-item :label="$t('couponfiles.user_list')" prop="user_list" required>-->
      <!--<el-col :span="20">-->
      <!--<el-radio-group v-model="postForm.user_list">-->
      <!--<el-radio :label="1">YES</el-radio>-->
      <!--<el-radio :label="0">NO</el-radio>-->
      <!--</el-radio-group>-->
      <!--</el-col>-->
      <!--</el-form-item>-->
      <el-form-item :label="$t('couponfiles.product')">
        <el-col :span="20">
          <el-transfer
            v-model="postForm.product"
            :props="{
              key: 'id',
              label: 'name'
            }"
            :titles="productTitle"
            :data="productList"
          />
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('couponfiles.location')">
        <el-col :span="20">
          <el-transfer
            v-model="postForm.location"
            :props="{
              key: 'id',
              label: 'name'
            }"
            :titles="locationTitle"
            :data="locationList"
          />
        </el-col>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDetailDialog">{{ $t('table.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm('postForm')">{{ $t('table.submit') }}</el-button>
    </div>

  </el-dialog>
</template>
<script>

import couponApi from '@/api/coupon/coupon'
import ScrollPane from '../../../../../components/ScrollPane/index'
import i18n from '@/lang/index'

const defaultForm = {
  area: '',
  is_available: 1,
  event_id: '',
  en_name: '',
  en_description: '',
  hk_name: '',
  hk_description: '',
  cn_name: '',
  cn_description: '',
  tw_name: '',
  tw_description: '',
  code: '',
  start_date: '',
  end_date: '',
  lang: '',
  user_limit: 1,
  user_list: 0,
  discount_type: 'AMOUNT',
  type: 1,
  location: [],
  product: [],
  couponrules: [{
    min_charge: '',
    min_cleanse_days: '',
    discount_off: ''
  }],
  symbol: 'HKD',
  exceed: 'Exceed',
  reduce: 'Reduce',
  discount: 'Discount'
}

export default {
  name: 'Detail',
  components: { ScrollPane },
  data() {
    return {
      activeName: 'first',
      postForm: Object.assign({}, defaultForm),
      rules: {
        area: [{ required: true, message: 'Area is required', trigger: 'change' }],
        discount_type: [{ required: true, message: 'Discount Type is required', trigger: 'change' }]
      },
      isEdit: false,
      areaList: [],
      imageUrl: '',
      recordid: 0,
      dialogTableVisible: false,
      menuList: [],
      selectedMenuOptions: [],
      permissionList: [],
      selectedPermissionOptions: [],
      permissionProps: {
        label: 'name',
        value: 'id',
        children: '_child'
      },
      productList: [],
      productTitle: [i18n.t('couponfiles.product'), i18n.t('couponfiles.use_product')],
      locationList: [],
      locationTitle: [i18n.t('couponfiles.location'), i18n.t('couponfiles.use_location')],
      typeList: []
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    },
    areaOptions: function() {
      return this.$store.state.locale.areas
    }
  },
  created() {
  },

  mounted() {

  },

  methods: {
    validDiscount(item) {
      if (this.postForm.discount_type === '1' || this.postForm.discount_type === 'AMOUNT') { // AMOUNT
        let t = false
        if (item.min_charge) {
          t = 0 < item.discount_off && item.discount_off < item.min_charge
          if (!t) {
            this.$message({
              type: 'error',
              message: 'The value of Discount is between Min. Charge and 0'
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: 'Please enter Min. Charge'
          })
        }
      } else { // PERCENTAGE
        let t2 = false
        t2 = 0 < item.discount_off && item.discount_off <= 1
        if (!t2) {
          this.$message({
            type: 'error',
            message: 'Discount can only be between 0 and 1'
          })
        }
      }
    },
    showRecord(id) {
      couponApi.showRecord(id).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.postForm = Object.assign({}, this.postForm, serviceResponse.data.record)
          this.productList = serviceResponse.data.productList
          this.locationList = serviceResponse.data.locationList
          this.postForm.location = serviceResponse.data.selectLocation
          this.postForm.product = serviceResponse.data.selectProduct
          this.postForm.couponrules = serviceResponse.data.couponrules
          this.typeList = serviceResponse.data.typeList
          //console.log(this.postForm.location, this.postForm.product)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleCreateRecord() {
      couponApi.createRecord().then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.productList = serviceResponse.data.productList
          this.locationList = serviceResponse.data.locationList
          this.typeList = serviceResponse.data.typeList
        }
      }).catch(err => {
        console.log(err)
      })
    },

    submitForm(formName) {
      let isTrue = true
      this.postForm.couponrules.forEach(item => {
        if (this.postForm.discount_type === '1' || this.postForm.discount_type === 'AMOUNT') { // AMOUNT
          let t = false
          if (item.min_charge) {
            t = 0 < item.discount_off && item.discount_off <= item.min_charge
            if (!t) {
              this.$message({
                type: 'error',
                message: 'The value of Discount is between Min. Charge and 0'
              })
              isTrue = false
            }
          } else {
            this.$message({
              type: 'error',
              message: 'Please enter Min. Charge'
            })
            isTrue = false
          }
        } else { // PERCENTAGE
          let t2 = false
          t2 = 0 < item.discount_off && item.discount_off < 1
          if (!t2) {
            this.$message({
              type: 'error',
              message: 'Discount can only be between 0 and 1'
            })
            isTrue = false
          }
        }
      })
      if (!isTrue) return
      this.$refs[formName].validate((valid) => {
        this.postForm.area = 96
        if (valid) {
          if (this.editId > 0) {
            couponApi.updateRecord(this.editId, this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  type: 'success',
                  message: serviceResponse.msg
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: serviceResponse.msg
                })
              }
            })
          } else {
            couponApi.storeRecord(this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  type: 'success',
                  message: serviceResponse.msg
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: serviceResponse.msg
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(postForm) {
      this.$refs[postForm].resetFields()
    },

    handShowDetailDialog(id) {
      this.postForm.couponrules.splice(0, this.postForm.couponrules.length)
      const item = {
        min_charge: '',
        min_cleanse_days: '',
        discount_off: ''
      }
      this.postForm.couponrules.push(item)

      this.selectedMenuOptions = []
      this.menuList = []
      this.selectedPermissionOptions = []
      this.permissionList = []
      if (id > 0) {
        this.isEdit = true
        this.editId = id
        this.showRecord(id)
      } else {
        this.isEdit = false
        this.handleCreateRecord()
        this.postForm = Object.assign({}, defaultForm)
      }
      this.dialogTableVisible = true
    },
    handleCloseDetailDialog() {
      this.resetForm('postForm')
      this.editId = 0
      this.$emit('indexRecord')
      this.dialogTableVisible = false
    },
    addcouponrule() {
      const item = {
        min_charge: '',
        min_cleanse_days: '',
        discount_off: ''
      }
      this.postForm.couponrules.push(item)
    },
    delcouponrule(index) {
      const len = this.postForm.couponrules.length
      if (len > 0) {
        this.postForm.couponrules.splice(index, 1)
      }
    },
    changearea() {
      const params = {
        area: this.postForm.area
      }

      const id = this.editId > 0 ? this.editId : 0

      couponApi.showAreaRecord(id, params).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.productList = serviceResponse.data.productList
          this.locationList = serviceResponse.data.locationList
          this.postForm.location = serviceResponse.data.selectLocation
          this.postForm.product = serviceResponse.data.selectProduct
          this.postForm.symbol = serviceResponse.data.symbol
          this.postForm.reduce = serviceResponse.data.reduce
          this.postForm.exceed = serviceResponse.data.exceed
          this.postForm.discount = serviceResponse.data.discount
        }
      }).catch(err => {
        console.log(err)
      })
    }
  }
}

</script>
